package cn.swenty.backstage.framework.common;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;

import cn.swenty.backstage.framework.common.model.Function;
import cn.swenty.backstage.framework.common.model.User;
import cn.swenty.backstage.framework.common.tree.TreeNode;
import cn.swenty.backstage.framework.common.util.StringUtil;

/**
 * 
 * 系统的一些方法
 * 
 * @author sunyang
 *
 */
public class Global {
	
	public final static String USER_SESSION = "USER_SESSION";
	
	
	/**
	 * 获取当前用户
	 * @return
	 */
	public static User  getCurrentUser(){
		
		return  (User)SecurityUtils.getSubject().getSession().getAttribute(USER_SESSION);
	}
	
	
	public static HttpSession getSession(){
		return (HttpSession) SecurityUtils.getSubject().getSession();
	}
	
	public static void setCurrentUser(User user){
		SecurityUtils.getSubject().getSession().setAttribute(USER_SESSION,user);
	}
	
	public List<Function> getFunctions(){
		return  ((User)SecurityUtils.getSubject().getSession().getAttribute(USER_SESSION)).getFunctions();
	}
	
	public static boolean hasCode(String code){
		if(StringUtil.isNull(code)){
			return false;
		}
		if(getCurrentUser().getFunctions() != null){
			List<Function> functions = getCurrentUser().getFunctions();
			for(Function function : functions){
				if(hasCode(code,function)){
					return true;
				}
			}
			
		}
		return false;
	}
	
	private static boolean hasCode(String code,Function function){
		if(function!=null && function.getChildren() !=null){
			for(TreeNode node : function.getChildren()){

				if(((Function)node).getFunction_code().equals(code)){
					return true;
				}else{
					if(hasCode(code,(Function)node)){
						return true;
					}
				}
			}
		}
		return false;
	}
	

}
